package timing.ukulele.form.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import timing.ukulele.form.persistent.FormTemplateHistory;
import timing.ukulele.form.service.FormTemplateHistoryService;
import timing.ukulele.form.service.FormTemplateService;
import timing.ukulele.form.service.VFormTemplateUnionService;
import timing.ukulele.common.Constant;
import timing.ukulele.common.ResponseResult;
import timing.ukulele.common.ResultCode;
import timing.ukulele.common.item.ItemData;
import timing.ukulele.form.persistent.FormTemplate;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.HashMap;
import java.util.List;

@RestController
@RequestMapping("/template")
@Api(tags = "表单模板接口")
public class FormTemplateController {
    private final FormTemplateService formTemplateService;
    private final FormTemplateHistoryService formTemplateHistoryService;
    private final VFormTemplateUnionService formTemplateUnionService;

    public FormTemplateController(FormTemplateService formTemplateService,
                                  FormTemplateHistoryService formTemplateHistoryService, VFormTemplateUnionService formTemplateUnionService) {
        this.formTemplateService = formTemplateService;
        this.formTemplateHistoryService = formTemplateHistoryService;
        this.formTemplateUnionService = formTemplateUnionService;
    }

    @GetMapping("/{id}")
    @ApiOperation("根据id获取模板信息")
    public ResponseResult<FormTemplate> findById(
            @ApiParam(value = "id", required = true, example = "1") @PathVariable("id") Long id) {
        FormTemplate template = formTemplateService.getBaseMapper().getTemplate(id);
        return ResponseResult.success(template);
    }

    @PostMapping("/create")
    @ApiOperation("保存模板")
    @ApiImplicitParam(name = "template", value = "模板对象", required = true, dataType = "FormTemplate")
    public ResponseResult<FormTemplate> create(@RequestBody FormTemplate template,
            @RequestHeader(Constant.USERNAME) String username) {
        template.setCreateBy(username);
        template.setUseId(0L);
        formTemplateService.save(template);
        return ResponseResult.success();
    }

    @PostMapping("/update")
    @ApiOperation("修改模板")
    @ApiImplicitParam(name = "template", value = "模板对象", required = true, dataType = "FormTemplate")
    public ResponseResult<FormTemplate> update(@RequestBody FormTemplate template,
                                               @RequestHeader(Constant.USERNAME) String username) {
        template.setUpdateBy(username);
        formTemplateService.updateById(template);
        return ResponseResult.success();
    }

    @DeleteMapping("/remove")
    @ApiOperation("删除模板")
    public ResponseResult<Boolean> remove(
            @ApiParam(value = "模板id", required = true, example = "1") @RequestParam Long id) {
        ResponseResult<List<ItemData>> items = formTemplateService.getItemByFormId(id);
        if (items == null || items.getCode() != ResultCode.SUCCESS.getCode()) {
            return ResponseResult.error("查询表单绑定的事项出错");
        }
        List<ItemData> itemList = items.getData();
        if (CollectionUtils.isEmpty(itemList)) {
            List<FormTemplateHistory> list = formTemplateHistoryService.lambdaQuery().eq(FormTemplateHistory::getUseId, id).list();
            if (CollectionUtils.isEmpty(list)) {
                formTemplateService.removeById(id);
            } else {
                return ResponseResult.error("当前表单已产生历史版本，不能删除");
            }
        } else {
            int count = itemList.size();
            String msg = String.format("当前表单已被绑定给以下%s事项(此处最多只显示5个)，不能删除.\n", count);
            if (count > 5)
                count = 5;
            for (int i = 0; i < count; i++) {
                msg += itemList.get(i).getName() + "\n";
            }
            return ResponseResult.error(msg);
        }
        return ResponseResult.success(Boolean.TRUE);
    }

    @GetMapping("/list")
    @ApiOperation("获取模板列表")
    public ResponseResult<List<FormTemplate>> list() {
        return ResponseResult.success(formTemplateService.list());
    }

    @GetMapping("/page")
    @ApiOperation("分页获取模板列表")
    public ResponseResult<IPage<FormTemplate>> page(
            @ApiParam(value = "查询名称") @RequestParam(value = "name", required = false) String name,
            @ApiParam(value = "当前页码", required = true, example = "1") @RequestParam Integer pageNum,
            @ApiParam(value = "每页大小", required = true, example = "10") @RequestParam Integer pageSize,
            @ApiParam(value = "正在使用版本id",example = "1") @RequestParam(required = false) Long useId,
            @ApiParam(value = "模板编码") @RequestParam(required = false) String code,
            @ApiParam(value = "所在系统名称") @RequestParam(required = false) String systemName,
            @ApiParam(value = "系统权限ID") @RequestHeader(Constant.SYSTEM) String systemIds) {
        // ){
        //     String systemIds = "1, 1326390830101028866, 1326391202156765185, 1326391346805727234, 1326391436677079042, 1326391548857933826, 1326391642428661761,"
        //         + "1326391804022611969, 1326391891947806721, 1326398858841829378, 1326807910528876546,1328902971995566081,1330761896646705153,1331786725621538817,1331798987254050817,"
        //         + "1331864533060300802,1341980290758352898,1422488072509575170";
        HashMap<String, Object> map = new HashMap<>();
        if (name != null) {
            map.put("name", name);
        }
        if (useId != null) {
            map.put("useId", useId);
        }
        if (code != null) {
            map.put("code", code);
        }
        if (systemName != null) {
            map.put("systemName", systemName);
        }
        return ResponseResult.success(formTemplateService.getPage(systemIds, pageNum, pageSize, map));
    }

    @GetMapping("/systemId/page")
    @ApiOperation("根据系统id获取表单模板列表")
    public ResponseResult<IPage<FormTemplate>> pageBySystemId(
            @ApiParam(value = "当前页码", required = true, example = "1") @RequestParam Integer pageNum,
            @ApiParam(value = "每页大小", required = true, example = "10") @RequestParam Integer pageSize,
            @ApiParam(value = "使用状态", example = "1") @RequestParam(required = false) Integer active,
            @ApiParam(value = "系统权限ID", example = "1") @RequestParam Long systemId) {
        return ResponseResult.success(formTemplateService.getPageBySystemId(systemId, pageNum, pageSize, active));
    }

    @GetMapping("/useId/page")
    @ApiOperation("分页获取指定模板的历史数据")
    public ResponseResult<IPage<FormTemplateHistory>> pageByUseId(
            @ApiParam(value = "查询名称") @RequestParam(value = "name", required = false) String name,
            @ApiParam(value = "当前页码", required = true, example = "1") @RequestParam Integer pageNum,
            @ApiParam(value = "每页大小", required = true, example = "10") @RequestParam Integer pageSize,
            @ApiParam(value = "正在使用版本id",example = "1") @RequestParam(required = false) Long useId,
            @ApiParam(value = "系统权限ID") @RequestHeader(Constant.SYSTEM) String systemIds) {
        HashMap<String, Object> map = new HashMap<>();
        if (useId != null) {
            map.put("useId", useId);
        }
        return ResponseResult.success(formTemplateHistoryService.page(name, systemIds, pageNum, pageSize, map));
    }

    @GetMapping("/item/page")
    @ApiOperation("事项下分页获取表单模板列表")
    public ResponseResult<Page<FormTemplate>> itemFormPage(
            @ApiParam(value = "当前页码", required = true, example = "1") @RequestParam Integer pageNum,
            @ApiParam(value = "每页大小", required = true, example = "10") @RequestParam Integer pageSize,
            @ApiParam(value = "表单模板id",example = "1") @RequestParam(required = false) Long templateId,
            @ApiParam(value = "系统id",example = "1") @RequestParam("systemId") Long systemId) {
        return ResponseResult.success((Page<FormTemplate>) formTemplateUnionService.getItemFormPage(systemId, templateId, pageNum, pageSize));
    }

    @PutMapping("/updateContent")
    @ApiOperation("修改模板")
    @ApiImplicitParam(name = "template", value = "模板对象", required = true, dataType = "FormTemplate")
    public ResponseResult<FormTemplate> updateContent(@RequestBody FormTemplate template,
                                                      @RequestHeader(Constant.USERNAME) String username) {
        if (template != null) {
            return formTemplateService.updateContent(template, username);
        }
        return ResponseResult.error("未找到该表单模板!");
    }

    @GetMapping("/getByItemCode")
    @ApiOperation("根据事项code获取事项关联的表单的信息")
    public ResponseResult<FormTemplate> getByItemCode(
            @ApiParam(value = "事项编码", required = true) @RequestParam(value = "itemCode") String itemCode) {
        return formTemplateService.getByItemCode(itemCode);
    }

    @PostMapping("/changeVersion")
    @ApiOperation("切换正在使用的模板版本")
    public ResponseResult<Boolean> changeVersion(
            @ApiParam(value = "需要切换版本的模板的id", required = true,example = "1") @RequestParam(value = "oldId") Long oldId,
            @ApiParam(value = "使用版本的模板的id", required = true,example = "1") @RequestParam(value = "newId") Long newId) {
        return ResponseResult.success(formTemplateService.changeVersion(oldId, newId));
    }

    @PostMapping("/saveTemplate")
    @ApiOperation("保存模板")
    @ApiImplicitParam(name = "template", value = "模板对象", required = true, dataType = "FormTemplate")
    public ResponseResult<FormTemplate> saveTemplate(
            @ApiParam(value = "模板对象", required = true) @RequestBody FormTemplate template,
            @RequestHeader(Constant.USERNAME) String username) {
        template.setCreateBy(username);
        template.setCreateTime(new Date());
        template.setUpdateTime(new Date());
        template.setUseId(0L);
        formTemplateService.saveTemplate(template);
        return ResponseResult.success();
    }

}
